import axios from 'axios'
import router from '@/router/index'
import { getmd5 } from '@/assets/js/common'

let len = 6;
let chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'; /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
let maxPos = chars.length;
let nonceStr = '';
for (let i = 0; i < len; i++) {
    nonceStr += chars.charAt(Math.floor(Math.random() * maxPos))
}

// http请求拦截器添加请求拦截器
axios.interceptors.request.use(function(config) {
    // 在发送请求之前做些什么
    let token = '';
    if (localStorage._token) {
        token = localStorage._token;
    } else {
        token = '';
        // token = '35f70407d597aa09907fe973c52d562b';
    }
    let query = "app_id=f1b396f5f8ff6adf&app_key=32001050f1b396f5f8ff6adf92c5c68b&random=" + nonceStr // app_id加上app_key上面拼好的字符串
        // let db_token = getmd5(token).toUpperCase() // 得到数据TOKEN并转大写
    let sign = getmd5(query).toUpperCase() // 生成签名并转大写
    config.headers.common['Authorization'] = 'Bearer ' + token; // 设置 axios 默认请求头
    // config.headers.common['sign'] = sign; // 设置 axios 默认请求头
    // config.headers.common['random'] = nonceStr; // 设置 axios 默认请求头
    // config.headers.common['timestamp'] = (new Date()).valueOf();

    return config;
}, function(error) {
    // 对请求错误做些什么
    this.$toast('网络异常');
    // console.log(error.response.data);
    return Promise.reject(error);
})

// axios.interceptors.response.use(data => {// 响应成功关闭loading
//     // loadinginstace.close()
//     return data
// }, error => {
//     // alert()
//     // loadinginstace.close();
//     return error.response
// })

// 添加响应拦截器
axios.interceptors.response.use(function(response) {
    // 对响应数据做点什么
    if (response.data.code == 401) {
        router.push({ name: "login" });
        return false;
    } else if (response.data.code == 403) {
        router.push({ name: "Error403" });
        return false;
    } else {
        return response
    }
}, function(error) {
    // 对响应错误做点什么
    // console.log(Promise.reject(error));
    // console.log(error.response.status);
    if (error.response.status == 500) {
        // return Promise.reject(error)
        //localStorage._token = "";
        router.push({ name: "Error500" });
        return false;
    } else if (error.response.status == 404) {
        router.push({ name: "Error404" });
        return false;
    } else {
        return Promise.reject(error)
    }
});
export default axios